package org.putrpctorest.parameter.impl;

import java.beans.PropertyDescriptor;
import java.util.List;

import org.putrpctorest.parameter.impl.log.MatchLog;

public class Flattner {

	private Definitions definitions;
	private MatchLog matchLog;

	public Flattner(Definitions definitions, MatchLog matchLog) {
		this.definitions = definitions;
		this.matchLog = matchLog;
	}

	public Definitions flatten() {
		matchLog.startFlatting(definitions);
		boolean atLeastOneWasFlattened = false;
		Definitions  flattenDefinitions = new Definitions(definitions.getDescription());
		for (Definition parameterDefinition : definitions) {
			List<PropertyDescriptor> readAndWriteBeanProperties = parameterDefinition
					.getReadAndWriteBeanProperties();
			if (readAndWriteBeanProperties.size() != 0) {
				for (PropertyDescriptor propertyDescritptor : readAndWriteBeanProperties) {
					flattenDefinitions.add(propertyDescritptor,
							parameterDefinition);
					atLeastOneWasFlattened = true;

				}
			} else {
				flattenDefinitions.add(parameterDefinition);
			}
		}
		if (atLeastOneWasFlattened) {
			return flattenDefinitions;
		} else {
			matchLog.flattenWasUnsuccessfull(definitions);
			return null;
		}
	}

}
